<?php
/**
 * Probably rewrite this class not to inherit from generic item
 *
 */
namespace Yz\modules\Uploads;
use FileError;
class Item_Upload
    extends \Yz_Item_Abstract
{

    protected $uploadPath;

    /**
     *  @var Yz_File
     */
    protected $file;


    /**************************
     *      Public methods    *
     **************************/



    /**
     *
     *  @return string path, relative to webRoot, with trailing slash
     */
    public function getUploadPath()
    {
        // get path relative to YZ_ROOT
        $path =& $this->uploadPath;
        if (! $path)
            $path = $this->model->getUploadPath();

        return $path;
    }

    /**
     *  @return Yz_File
     */
    public function getFile()
    {
        debug();
        $file =& $this->file;
        if (null === $file) {
            $link = $this->getLinkToFile();
            if (null !== $link)
                $file = new \Yz_File($link, YZ_ROOT);
            else
                $file = null;

        }
        return $file;
    }

    /** get the link to file, relative to web root
     *
     *  @return string|null
     */
    public function getLinkToFile()
    {
        debug();
        $fn = $this->filename;
        if (null !== $fn) {
            $path = $this->getUploadPath();
            $link = $path.'/'.$fn;
        } else {
            $link = null;
        }
        return $link;
    }

    /** get the HTML code for displaying
     *
     *  @return string|null
     */
    public function buildHTML(\Yz_Template_Interface $t)
    {
        debug();
        $fn = $this->filename;
        if (null === $fn)
            return null;
        $link = $this->getUploadPath()
            . '/'
            . rawurlencode($fn)
        ;
        $fn = \Yz_String::toHTML($fn);

        $html = <<<html
            <a href="{$t->webRoot}{$link}">{$fn}</a>\n
html;
        return $html;
    }

    /**
     *
     *  @return string absolute path with trailing slash
     */
    public function getUploadPathAbsolute()
    {
        // get path relative to YZ_ROOT
        $path = $this->getUploadPath();
        $path = YZ_ROOT . trim($path, '/') . '/';
        if (! is_dir($path))
            throw FileError::_new_(array('path' => $path));

        return $path;
    }

} // class
